<?php

namespace common\models\shop;

use Yii;

/**
 * This is the model class for table "{{%shop_goods_stock}}".
 *
 * @property int $id
 * @property string $goods_id 商品ID
 * @property string $total 商品数量
 * @property string $shelf 上架数
 * @property string $stock 库存
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class ShopGoodsStock extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%shop_goods_stock}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['goods_id', 'total', 'shelf', 'stock', 'created_at', 'updated_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'goods_id' => '商品ID',
            'total' => '商品数量',
            'shelf' => '上架数',
            'stock' => '库存',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public static function reduce($condition, $number) {
        $model = static::findOne($condition);
        $model->stock = $model->stock - $number;
        return $model->save();
    }

    public static function revert($condition, $number) {
        $model = static::findOne($condition);
        $model->stock = $model->stock + $number;
        return $model->save();
    }

    public function getUseStock() {
        return $this->stock - $this->total + $this->shelf;
    }

    public function getStocks($id) {
        $keystock = 'goods_stock_' . $id;
        $cache = Yii::$app->cache;
        return $cache->getOrSet($keystock, function ($cache) use ($id) {
            $model = static::findOne(['goods_id' => $id]);
            return $model->stock;
        }, 1000);
    }

    public static function stock($id) {
        $keystock = 'goods_stock_' . $id;
        $cache = Yii::$app->cache;
        return $cache->getOrSet($keystock, function ($cache) use ($id) {
            $model = static::findOne(['goods_id' => $id]);
            return $model->stock;
        });
    }

}
